<?php
/**
 * @Author: liuhongbin
 * @Email: 514660094@qq.com
 * @Date: 2019-02-12 16:15:10
 * @Description:
 * @LastEditors: liuhongbin
 * @LastEditTime: xxx
 */

namespace addons\cloud_market\controller\api\docs;

use addons\cloud_market\controller\api\CloudMarketApiController;
use addons\cloud_market\model\CloudMarketAddon;
use addons\cloud_market\model\CloudMarketDocs;
use addons\cloud_market\model\CloudMarketDocsContent;
use addons\cloud_market\model\CloudMarketOrder;
use hiduoke\services\FormBuilder as Form;

class Docs extends CloudMarketApiController
{

    protected $notApiCheck = ['*'];
    protected $notApiLogin = ['getList', 'getContentById', 'showByNoUser'];

    public function initialize()
    {
        parent::initialize();
        $this->model = new CloudMarketDocs();
    }

    public function getList()
    {
        $res = $this->model->getPageList();
        $data = $res['data'];
        return $this->success($res['count'], $data);
    }

    public function show($id)
    {
        $docs = $this->model->where(['id' => $id])->find();
        if (!$docs) {
            return $this->error('未找到文档');
        }
        $docs = $docs->append(['content_list']);
        return $this->success('ok', $docs);
    }


    /**
     * Create by :  刘泓宾<514660094@qq.com>
     * @param $id
     * @param $content_id
     */
    public function showByNoUser($id, $content_id = 0)
    {
        $docs = $this->model->where(['id' => $id])->append(['user'])->find();
        if (!$docs) {
            return $this->error('未找到文档');
        }
        // 查看权限
        $see = 1;
        $contentModel = new CloudMarketDocsContent();
        $user = $this->getUser();
        $addon = (new CloudMarketAddon())
            ->where(['id' => $docs['addon_id']])
            ->field(['id', 'title', 'icon_image', 'price', 'name'])
            ->append(['icon_image_url'])->find();

        // 判断当前文档权限 public=公开,login=登录,dev=开发者,addon=购买模块,keyword=口令访问
        if ($content_id == 0) {
            $content = $contentModel->where(['docs_id' => $id])->order('sort', 'asc')->findOrEmpty();
//            if ($content['access'] != 'public') {
//                $see = 0;
//            }
        } else {
            $content = $contentModel->where(['id' => $content_id, 'docs_id' => $id])->find();
        }
        switch ($content['access']) {
            case 'public':
                break;
            case 'login':
                if (!$user) {
                    $see = 0;
                }
                break;
            case 'dev':
                if (!$user) {
                    $see = 0;
                    break;
                }
                if (!$user['developer']) {
                    $see = 0;
                }
                break;
            case 'addon':
                if ($docs['addon_id']) {
                    if (!$user) {
                        $see = 0;
                        break;
                    }
                    // 判断订单是否有
                    $order_count = (new CloudMarketOrder())->where(['user_id' => $user['id'], 'aid' => $docs['addon_id'], 'status' => 1])->count();
                    if (empty($order_count)) {
                        $see = 0;
                    }
                }
                break;
            case 'keyword':
                if ($content['keyword'] && $content['keyword'] != $this->request->param('keyword')) {
                    $see = 0;
                }
                break;
        }


        if (!$see) {
            $content['content'] = "";
            $content['keyword'] = "";
        }
        return $this->success('ok', [
            'docs'         => $docs,
            'content_list' => $docs->content_list,
            'content'      => $content,
            'see'          => $see,
            'addon'        => $addon,
            'access'       => $content['access']
        ]);
    }

    public function getForm($id)
    {
        $row = $this->model->findOrEmpty($id);//创建表单
        $form = Form::createForm("/api.docs.docs/save?id=" . $id)->setMethod("POST");
        $user = $this->getUser();
        if ($id && $row['user_id'] != $user['id']) {
            return $this->error('非法操作,你没有权限');
        }
        $dev_id = $user['developer']['id'] ?? 0;
        if (!$dev_id) {
            return $this->error('仅开发者可创建,你没有权限');
        }
        $docs_addon_names = (new CloudMarketDocs())->where(['user_id' => $user['id']])->column('name');
        if ($user['id'] != '1') {
            $bind_addon = '1';
            $bind_addon_disabled = true;
        } else {
            $bind_addon = $row['config']['bind_addon'] ?? '0';
            $bind_addon_disabled = false;
        }
        //新增表单
        $rule = [
            Form::input('title', '文档标题', $row['title'] ?? '')->required(),
            Form::switches('config_bind_addon', '绑定应用', $bind_addon)->appendControl('1', [
                Form::select('addon_id', '绑定应用', $row['addon_id'] ?? '')->options(
                    function () use ($user, $docs_addon_names) {
                        $options = [];
                        if ($user['developer']) {
                            $list = (new CloudMarketAddon())->where(['dev_id' => $user['developer']['id']])->select();
                            foreach ($list as $item) {
                                $option = ['value' => $item['id'], 'label' => $item['title'] . '(' . $item['name'] . ')'];
                                if (in_array($item['name'], $docs_addon_names)) {
                                    $option['disabled'] = true;
                                }
                                $options[] = $option;
                            }
                        }
                        return $options;
                    }
                )->filterable(true)
            ])->appendControl('0', [
                Form::input('name', '文档标识', $row['name'] ?? '')->effect(['help' => '不填写则默认为文档id'])->required()
            ])->disabled($bind_addon_disabled),

            Form::input('desc', '文档描述', $row['desc'] ?? '')->required(),
            Form::dkImage('image', '文档封面', $row['image'] ?? '')->required(),
        ];
        $title = !$id ? "新增" : "编辑";
        $form->setTitle($title)->setRule($rule);
        return $this->success("", Form::getFormData($form), $docs_addon_names);
    }

    public function save($id = 0)
    {
        $user = $this->getUser();
        $row = $this->model->findOrEmpty($id);
        if ($id && $row['user_id'] != $user['id']) {
            return $this->error('非法操作,你没有权限');
        }
        $formData = getFormData();
        $addon_id = $formData['addon_id'] ?? 0;
        $addon_name = (new CloudMarketAddon())->where(['id' => $addon_id])->value('name') ?? '';
        // 没有填写应用
        if (!$addon_name && $formData['name']) {
            // 判断是否和模块名一致
            $addon_name = (new CloudMarketAddon())->where(['name' => $formData['name']])->value('name') ?? '';
            if ($addon_name) {
                return $this->error('文档标识不可以和模块名称一致');
            }
        }
        $formData['name'] = $addon_name ?: $formData['name'];
        if ($formData['name'] && $formData['name'] != $row['name']) {
            $docs = (new CloudMarketDocs())->where(['name' => $formData['name']])->find();
            if ($docs) {
                if ($addon_name) {
                    return $this->error('当前应用标识已存在');
                } else {
                    return $this->error('当前文档标识已存在');
                }
            }
        }
        $formData['user_id'] = $user['id'];
        $row->save($formData);
        return $this->success($id ? '保存成功' : '创建成功', ['formData' => $formData, 'row' => $row]);
    }

    public function delete($id)
    {
        $user = $this->getUser();
        $row = $this->model->findOrEmpty($id);
        if ($id && $row['user_id'] != $user['id']) {
            return $this->error('非法操作,你没有权限');
        }
        $row->delete();
        (new CloudMarketDocsContent())->where(['docs_id' => $id])->delete();
        return $this->success("删除成功");
    }
}
